package com.example.controller;

import com.example.pojo.Employee;
import com.example.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/employees")
    public Map<String, Object> getEmployees(@RequestParam int page, @RequestParam int limit) {
        List<Employee> employees = employeeService.getEmployees(page, limit);
        int total = employeeService.getTotalEmployees();

        Map<String, Object> response = new HashMap<>();
        response.put("total", total);
        response.put("page", page);
        response.put("limit", limit);
        response.put("employees", employees);

        return response;
    }

    @GetMapping("/employee/{employeeId}")
    public Employee getEmployeeById(@PathVariable String employeeId) {

        return employeeService.getEmployeeById(employeeId);
    }

    @GetMapping("/employee/search")
    public Map<String, Object> getEmployeeByName(
            @RequestParam String name,
            @RequestParam int page,
            @RequestParam int limit) {

        int offset = (page - 1) * limit;
        List<Employee> employees = employeeService.getEmployeeByName(name, offset, limit);
        int total = employeeService.countEmployeesByName(name);

        Map<String, Object> response = new HashMap<>();
        if (employees.isEmpty()) {
            response.put("status", "error");
            response.put("message", "Employee not found.");
        } else {
            response.put("status", "success");
            response.put("total", total);
            response.put("page", page);
            response.put("limit", limit);
            response.put("employees", employees);
        }

        return response;
    }
}
